#!/bin/bash

# Health Check 安装脚本
# 安装 systemd 服务和监控脚本

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
INSTALL_DIR="/opt/health-check"
SERVICE_NAME="health-check"

# 检查是否为 root 用户
if [ "$EUID" -ne 0 ]; then
    echo "请使用 root 用户运行此脚本"
    exit 1
fi

echo "开始安装 Health Check..."

# 检查并构建程序
echo "检查程序文件..."
if [ ! -f "$PROJECT_DIR/health-check" ]; then
    echo "程序文件不存在，开始构建..."
    cd "$PROJECT_DIR"
    
    # 检查 Go 环境
    if ! command -v go &> /dev/null; then
        echo "错误: 未找到 Go 环境，请先安装 Go"
        exit 1
    fi
    
    # 下载依赖
    echo "下载依赖..."
    go mod tidy
    
    # 构建程序
    echo "构建程序..."
    go build -o health-check cmd/main.go
    
    if [ $? -ne 0 ]; then
        echo "错误: 程序构建失败"
        exit 1
    fi
    
    echo "程序构建成功"
else
    echo "程序文件已存在，跳过构建"
fi

# 创建安装目录
echo "创建安装目录: $INSTALL_DIR"
mkdir -p "$INSTALL_DIR"
mkdir -p "$INSTALL_DIR/logs"

# 复制程序文件
echo "复制程序文件..."
cp "$PROJECT_DIR/health-check" "$INSTALL_DIR/"

# 复制整个 configs 目录
echo "复制配置文件..."
cp -r "$PROJECT_DIR/configs" "$INSTALL_DIR/"

cp "$PROJECT_DIR/scripts/start.sh" "$INSTALL_DIR/"

# 设置权限
chmod +x "$INSTALL_DIR/health-check"
chmod +x "$INSTALL_DIR/start.sh"
chown -R root:root "$INSTALL_DIR"

# 安装 systemd 服务
echo "安装 systemd 服务..."
cp "$SCRIPT_DIR/health-check.service" "/etc/systemd/system/"
systemctl daemon-reload
systemctl enable "$SERVICE_NAME"

# 创建日志目录
mkdir -p "/var/log"
touch "/var/log/health-check-daemon.log"
chown root:root "/var/log/health-check-daemon.log"

echo "安装完成！"
echo ""
echo "使用方法:"
echo "  systemctl start $SERVICE_NAME    # 启动服务"
echo "  systemctl stop $SERVICE_NAME     # 停止服务"
echo "  systemctl restart $SERVICE_NAME  # 重启服务"
echo "  systemctl status $SERVICE_NAME   # 查看状态"
echo "  journalctl -u $SERVICE_NAME -f   # 查看日志"
echo ""
echo "或者使用监控脚本:"
echo "  $INSTALL_DIR/start.sh start      # 启动"
echo "  $INSTALL_DIR/start.sh stop       # 停止"
echo "  $INSTALL_DIR/start.sh restart    # 重启"
echo "  $INSTALL_DIR/start.sh status     # 状态"
echo "  $INSTALL_DIR/start.sh monitor    # 监控模式"
echo ""
echo "配置文件位置: $INSTALL_DIR/configs/config.yaml"
echo "日志文件位置: $INSTALL_DIR/logs/health-check.log"
